#!/usr/bin/env python3
"""
Integration Validator for Intelligent Rules V2.0
验证用户项目是否正确集成了intelligent_rules_v2通用底座

Usage: python intelligent_rules_v2/tools/integration_validator.py
"""

import os
import sys
import yaml
from pathlib import Path
from typing import Dict, List, Any, Optional

class IntegrationValidator:
    """集成验证器 - 检查用户项目集成状态"""
    
    def __init__(self, user_project_root: Optional[Path] = None):
        # 用户项目根目录（包含intelligent_rules_v2子模块的目录）
        self.user_project_root = user_project_root or Path.cwd()
        self.intelligent_rules_path = self.user_project_root / "intelligent_rules_v2"
        
        self.errors = []
        self.warnings = []
        self.info = []
        
    def validate_integration(self) -> Dict[str, Any]:
        """验证集成状态"""
        
        print("🔍 验证 intelligent_rules_v2 集成状态")
        print("=" * 60)
        print(f"用户项目路径: {self.user_project_root}")
        print(f"通用底座路径: {self.intelligent_rules_path}")
        print()
        
        # 1. 验证子模块存在
        self._validate_submodule_exists()
        
        # 2. 验证用户项目结构
        self._validate_user_project_structure()
        
        # 3. 验证配置文件
        self._validate_user_config()
        
        # 4. 验证规则集成
        self._validate_rules_integration()
        
        # 5. 验证智能演进可用性
        self._validate_evolution_readiness()
        
        # 生成集成报告
        return self._generate_integration_report()
    
    def _validate_submodule_exists(self):
        """验证子模块存在"""
        print("📦 验证子模块...")
        
        if not self.intelligent_rules_path.exists():
            self.errors.append("未找到 intelligent_rules_v2 子模块")
            self.errors.append("请运行: git submodule add <url> intelligent_rules_v2")
            return
            
        # 检查子模块关键组件
        required_components = [
            "foundation/core",
            "rules/core",
            "coordination",
            "tools/config_validator.py"
        ]
        
        for component in required_components:
            component_path = self.intelligent_rules_path / component
            if not component_path.exists():
                self.errors.append(f"子模块缺少关键组件: {component}")
            else:
                self.info.append(f"✅ 子模块组件: {component}")
        
        # 检查子模块版本
        readme_path = self.intelligent_rules_path / "README.md"
        if readme_path.exists():
            try:
                with open(readme_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    if "V2.0" in content:
                        self.info.append("✅ 子模块版本: V2.0")
                    else:
                        self.warnings.append("无法确认子模块版本")
            except:
                self.warnings.append("无法读取子模块README")
    
    def _validate_user_project_structure(self):
        """验证用户项目结构"""
        print("\n🏗️ 验证用户项目结构...")
        
        # 建议的目录结构（不强制）
        suggested_dirs = {
            "rules": "用户项目专属规则",
            "config": "用户项目配置", 
            "src": "用户项目源码"
        }
        
        for dir_name, description in suggested_dirs.items():
            dir_path = self.user_project_root / dir_name
            if dir_path.exists():
                self.info.append(f"✅ {dir_name}/ - {description}")
            else:
                self.warnings.append(f"建议创建 {dir_name}/ 目录用于{description}")
        
        # 检查是否有冲突的目录名
        conflict_dirs = ["foundation", "coordination"]
        for dir_name in conflict_dirs:
            dir_path = self.user_project_root / dir_name
            if dir_path.exists():
                self.warnings.append(f"发现可能冲突的目录: {dir_name}/ (与子模块同名)")
    
    def _validate_user_config(self):
        """验证用户配置"""
        print("\n⚙️ 验证用户配置...")
        
        # 检查用户项目配置
        config_files = [
            "config/project.yaml",
            "config/app.yaml",
            ".intelligent_rules.yaml"  # 可选的简化配置
        ]
        
        config_found = False
        for config_file in config_files:
            config_path = self.user_project_root / config_file
            if config_path.exists():
                config_found = True
                self.info.append(f"✅ 配置文件: {config_file}")
                
                # 验证配置内容
                try:
                    with open(config_path, 'r', encoding='utf-8') as f:
                        config = yaml.safe_load(f)
                    
                    # 检查是否引用了intelligent_rules_v2
                    if self._config_references_intelligent_rules(config):
                        self.info.append(f"✅ {config_file} 正确引用了 intelligent_rules_v2")
                    else:
                        self.warnings.append(f"{config_file} 未引用 intelligent_rules_v2")
                        
                except Exception as e:
                    self.errors.append(f"配置文件 {config_file} 格式错误: {str(e)}")
        
        if not config_found:
            self.warnings.append("未找到用户项目配置文件")
            self.warnings.append("建议创建 config/project.yaml 配置文件")
    
    def _config_references_intelligent_rules(self, config: Dict[str, Any]) -> bool:
        """检查配置是否引用了intelligent_rules_v2"""
        
        # 检查常见的引用方式
        if "intelligent_rules" in config:
            return True
        if "intelligent_rules_v2" in str(config):
            return True
        if isinstance(config, dict):
            for value in config.values():
                if isinstance(value, dict) and self._config_references_intelligent_rules(value):
                    return True
        return False
    
    def _validate_rules_integration(self):
        """验证规则集成"""
        print("\n📜 验证规则集成...")
        
        user_rules_dir = self.user_project_root / "rules"
        if not user_rules_dir.exists():
            self.warnings.append("用户项目没有 rules/ 目录")
            return
        
        # 检查用户规则目录结构
        suggested_rule_dirs = ["core", "evolution", "system", "validation"]
        
        for rule_dir in suggested_rule_dirs:
            rule_path = user_rules_dir / rule_dir
            if rule_path.exists():
                # 统计规则文件
                rule_files = list(rule_path.glob("*.yaml"))
                if rule_files:
                    self.info.append(f"✅ 用户规则: {rule_dir}/ ({len(rule_files)} 个文件)")
                else:
                    self.warnings.append(f"规则目录 {rule_dir}/ 为空")
            else:
                self.warnings.append(f"建议创建 rules/{rule_dir}/ 目录")
        
        # 检查是否有规则文件引用了底座规则
        self._check_rule_references()
    
    def _check_rule_references(self):
        """检查规则文件引用"""
        
        user_rules_dir = self.user_project_root / "rules"
        if not user_rules_dir.exists():
            return
            
        # 搜索引用底座规则的文件
        rule_files = list(user_rules_dir.rglob("*.yaml"))
        referenced_files = 0
        
        for rule_file in rule_files:
            try:
                with open(rule_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    if "intelligent_rules_v2" in content or "foundation" in content:
                        referenced_files += 1
            except:
                continue
        
        if referenced_files > 0:
            self.info.append(f"✅ {referenced_files} 个规则文件引用了通用底座")
        else:
            self.warnings.append("用户规则文件未引用通用底座规则")
    
    def _validate_evolution_readiness(self):
        """验证智能演进就绪状态"""
        print("\n🔄 验证智能演进就绪状态...")
        
        # 检查是否能导入演进引擎
        try:
            sys.path.insert(0, str(self.intelligent_rules_path))
            from foundation.core.intelligent_evolution_engine import get_global_evolution_engine
            
            self.info.append("✅ 智能演进引擎可用")
            
            # 尝试创建引擎实例
            try:
                engine = get_global_evolution_engine()
                self.info.append("✅ 演进引擎初始化成功")
            except Exception as e:
                self.warnings.append(f"演进引擎初始化警告: {str(e)}")
                
        except ImportError as e:
            self.errors.append(f"无法导入演进引擎: {str(e)}")
        except Exception as e:
            self.errors.append(f"演进引擎检查失败: {str(e)}")
        finally:
            # 清理sys.path
            if str(self.intelligent_rules_path) in sys.path:
                sys.path.remove(str(self.intelligent_rules_path))
    
    def _generate_integration_report(self) -> Dict[str, Any]:
        """生成集成报告"""
        
        print("\n" + "=" * 60)
        print("📊 集成验证报告")
        print("=" * 60)
        
        # 显示错误
        if self.errors:
            print(f"\n❌ 错误 ({len(self.errors)}个):")
            for error in self.errors:
                print(f"  • {error}")
        
        # 显示警告
        if self.warnings:
            print(f"\n⚠️ 警告 ({len(self.warnings)}个):")
            for warning in self.warnings:
                print(f"  • {warning}")
        
        # 显示信息
        if self.info:
            print(f"\n✅ 验证通过 ({len(self.info)}个):")
            for info in self.info:
                print(f"  • {info}")
        
        # 集成状态评估
        total_checks = len(self.errors) + len(self.warnings) + len(self.info)
        success_rate = len(self.info) / total_checks * 100 if total_checks > 0 else 0
        
        print(f"\n📈 集成状态评估:")
        print(f"  总检查项: {total_checks}")
        print(f"  成功率: {success_rate:.1f}%")
        
        if len(self.errors) == 0:
            if len(self.warnings) == 0:
                print(f"  状态: 🟢 完美集成")
                recommendations = []
            else:
                print(f"  状态: 🟡 良好集成 (有{len(self.warnings)}个建议)")
                recommendations = [
                    "创建用户项目配置文件",
                    "建立项目专属规则目录",
                    "配置智能演进参数"
                ]
        else:
            print(f"  状态: 🔴 集成问题 (需要解决{len(self.errors)}个错误)")
            recommendations = [
                "检查子模块是否正确添加",
                "验证子模块完整性",
                "检查依赖项安装"
            ]
        
        print(f"\n💡 建议的后续步骤:")
        default_recommendations = [
            "运行智能演进引擎: python intelligent_rules_v2/foundation/core/intelligent_evolution_engine.py",
            "创建项目专属规则: 在 rules/ 目录下添加业务规则",
            "配置演进参数: 在 config/ 目录下设置项目配置"
        ]
        
        all_recommendations = recommendations + default_recommendations
        for i, rec in enumerate(all_recommendations[:5], 1):
            print(f"  {i}. {rec}")
        
        return {
            "total_checks": total_checks,
            "success_rate": success_rate,
            "errors": self.errors,
            "warnings": self.warnings,
            "info": self.info,
            "status": "perfect" if len(self.errors) == 0 and len(self.warnings) == 0 
                     else "good" if len(self.errors) == 0 
                     else "needs_attention",
            "recommendations": all_recommendations
        }

def main():
    """主程序"""
    print("🔧 Intelligent Rules V2.0 集成验证器")
    print("验证用户项目是否正确集成了通用底座")
    print()
    
    # 检查是否在用户项目根目录运行
    current_dir = Path.cwd()
    if current_dir.name == "intelligent_rules_v2":
        print("⚠️ 检测到在 intelligent_rules_v2 目录内运行")
        print("建议在包含 intelligent_rules_v2 子模块的用户项目根目录运行")
        print()
        
        # 尝试找到父目录
        parent_dir = current_dir.parent
        if (parent_dir / "intelligent_rules_v2").exists():
            print(f"自动切换到用户项目目录: {parent_dir}")
            validator = IntegrationValidator(parent_dir)
        else:
            print("继续在当前目录验证...")
            validator = IntegrationValidator()
    else:
        validator = IntegrationValidator()
    
    result = validator.validate_integration()
    
    # 退出码
    exit_code = 0 if result["status"] in ["perfect", "good"] else 1
    
    print(f"\n🎯 集成验证完成，退出码: {exit_code}")
    sys.exit(exit_code)

if __name__ == "__main__":
    main() 